package com.example.chamberlainserver.controller;

import com.example.chamberlainserver.Service.UserAvailabilityService;
import com.example.chamberlainserver.Entry.UserAvailability;
import com.example.chamberlainserver.security.JwtTokenUtil;
import com.example.chamberlainserver.Vo.Response.ApiResponse;
import com.example.chamberlainserver.dto.PageResult;
import com.example.chamberlainserver.dto.TimeSlotRequestDTO;
import com.example.chamberlainserver.dto.TimeSlotResponseDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户可用时间控制器
 * 包含用户可用时间管理和时间填报相关功能
 */
@RestController
@RequestMapping("/schedule/availability")
public class UserAvailabilityController {

    @Autowired
    private UserAvailabilityService userAvailabilityService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    /**
     * 添加用户可用时间
     */
    @PostMapping("/add")
    @PreAuthorize("hasRole('COUNSELOR') or hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<Void>> addUserAvailability(@RequestBody UserAvailability userAvailability) {
        try {
            boolean success = userAvailabilityService.addUserAvailability(userAvailability);

            if (success) {
                return ResponseEntity.ok(ApiResponse.success("添加用户可用时间成功", null));
            } else {
                return ResponseEntity.ok(ApiResponse.error("添加用户可用时间失败"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("添加用户可用时间失败: " + e.getMessage()));
        }
    }

    /**
     * 批量添加用户可用时间
     */
    @PostMapping("/batchAdd")
    @PreAuthorize("hasRole('COUNSELOR') or hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<Void>> batchAddUserAvailability(@RequestBody List<UserAvailability> userAvailabilityList) {
        try {
            boolean success = userAvailabilityService.batchAddUserAvailability(userAvailabilityList);

            if (success) {
                return ResponseEntity.ok(ApiResponse.success("批量添加用户可用时间成功", null));
            } else {
                return ResponseEntity.ok(ApiResponse.error("批量添加用户可用时间失败"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("批量添加用户可用时间失败: " + e.getMessage()));
        }
    }

    /**
     * 根据ID获取用户可用时间
     */
    @GetMapping("/get/{id}")
    public ResponseEntity<ApiResponse<UserAvailability>> getUserAvailabilityById(@PathVariable String id) {
        try {
            UserAvailability userAvailability = userAvailabilityService.getUserAvailabilityById(id);

            if (userAvailability != null) {
                return ResponseEntity.ok(ApiResponse.success("获取用户可用时间成功", userAvailability));
            } else {
                return ResponseEntity.ok(ApiResponse.error(404, "用户可用时间不存在"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取用户可用时间失败: " + e.getMessage()));
        }
    }

    /**
     * 根据用户ID获取可用时间列表 - 简化数据结构
     */
    @GetMapping("/time-report")
    public ResponseEntity<ApiResponse<TimeSlotResponseDTO>> getUserAvailabilityByUserId(
            HttpServletRequest httpRequest) {
        try {
            // 从请求头中获取JWT token并解析用户ID
            String authorizationHeader = httpRequest.getHeader("Authorization");
            if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
                return ResponseEntity.ok(ApiResponse.error("未找到有效的认证token"));
            }

            String token = authorizationHeader.substring(7); // 移除"Bearer "前缀
            Integer userId;
            try {
                userId = jwtTokenUtil.getUserIdFromToken(token);
                if (userId == null) {
                    return ResponseEntity.ok(ApiResponse.error("无法从token中获取用户ID"));
                }
            } catch (Exception e) {
                return ResponseEntity.ok(ApiResponse.error("token解析失败: " + e.getMessage()));
            }
            System.out.println("根据用户ID获取可用时间列表 --> User ID: " + userId);
            TimeSlotResponseDTO timeSlots = userAvailabilityService.getUserTimeSlots(userId);
            return ResponseEntity.ok(ApiResponse.success("获取用户可用时间列表成功", timeSlots));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取用户可用时间列表失败: " + e.getMessage()));
        }
    }

    /**
     * 根据星期几获取可用用户列表
     */
    @GetMapping("/dayOfWeek/{dayOfWeek}")
    @PreAuthorize("hasRole('COUNSELOR') or hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<List<UserAvailability>>> getAvailableUsersByDayOfWeek(@PathVariable Integer dayOfWeek) {
        try {
            List<UserAvailability> userAvailabilityList = userAvailabilityService.getAvailableUsersByDayOfWeek(dayOfWeek);
            return ResponseEntity.ok(ApiResponse.success("获取可用用户列表成功", userAvailabilityList));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取可用用户列表失败: " + e.getMessage()));
        }
    }

    /**
     * 更新用户可用时间
     */
    @PutMapping("/update")
    @PreAuthorize("hasRole('COUNSELOR') or hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<Void>> updateUserAvailability(@RequestBody UserAvailability userAvailability) {
        try {
            boolean success = userAvailabilityService.updateUserAvailability(userAvailability);

            if (success) {
                return ResponseEntity.ok(ApiResponse.success("更新用户可用时间成功", null));
            } else {
                return ResponseEntity.ok(ApiResponse.error("更新用户可用时间失败"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("更新用户可用时间失败: " + e.getMessage()));
        }
    }

    /**
     * 删除用户可用时间
     */
    @DeleteMapping("/delete/{id}")
    @PreAuthorize("hasRole('COUNSELOR') or hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<Void>> deleteUserAvailability(@PathVariable String id) {
        try {
            boolean success = userAvailabilityService.deleteUserAvailability(id);

            if (success) {
                return ResponseEntity.ok(ApiResponse.success("删除用户可用时间成功", null));
            } else {
                return ResponseEntity.ok(ApiResponse.error("删除用户可用时间失败"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("删除用户可用时间失败: " + e.getMessage()));
        }
    }

    /**
     * 删除用户的所有可用时间
     */
    @DeleteMapping("/deleteByUser/{userId}")
    @PreAuthorize("hasRole('COUNSELOR') or hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<Void>> deleteUserAvailabilityByUserId(@PathVariable Integer userId) {
        try {
            boolean success = userAvailabilityService.deleteUserAvailabilityByUserId(userId);

            if (success) {
                return ResponseEntity.ok(ApiResponse.success("删除用户可用时间成功", null));
            } else {
                return ResponseEntity.ok(ApiResponse.error("删除用户可用时间失败"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("删除用户可用时间失败: " + e.getMessage()));
        }
    }

    /**
     * 分页查询用户可用时间列表
     */
    @GetMapping("/pagedList")
    @PreAuthorize("hasRole('COUNSELOR') or hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<PageResult<UserAvailability>>> getPagedUserAvailabilityList(
            @RequestParam(value = "current", required = false, defaultValue = "1") Integer current,
            @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize,
            @RequestParam(value = "userId", required = false) Integer userId,
            @RequestParam(value = "dayOfWeek", required = false) Integer dayOfWeek,
            @RequestParam(value = "isAvailable", required = false) Boolean isAvailable) {
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("current", current);
            params.put("pageSize", pageSize);
            params.put("offset", (current - 1) * pageSize);

            if (userId != null) {
                params.put("userId", userId);
            }
            if (dayOfWeek != null) {
                params.put("dayOfWeek", dayOfWeek);
            }
            if (isAvailable != null) {
                params.put("isAvailable", isAvailable);
            }

            PageResult<UserAvailability> pageResult = userAvailabilityService.getPagedUserAvailabilityList(params);
            return ResponseEntity.ok(ApiResponse.success("获取用户可用时间列表成功", pageResult));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取用户可用时间列表失败: " + e.getMessage()));
        }
    }

    /**
     * 更新用户周可用时间
     */
    @PutMapping("/updateWeekly/{userId}")
    @PreAuthorize("hasRole('COUNSELOR') or hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<Void>> updateUserWeeklyAvailability(
            @PathVariable Integer userId,
            @RequestBody List<UserAvailability> weeklyAvailability) {
        try {
            boolean success = userAvailabilityService.updateUserWeeklyAvailability(userId, weeklyAvailability);

            if (success) {
                return ResponseEntity.ok(ApiResponse.success("更新用户周可用时间成功", null));
            } else {
                return ResponseEntity.ok(ApiResponse.error("更新用户周可用时间失败"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("更新用户周可用时间失败: " + e.getMessage()));
        }
    }

    /**
     * 用户选择空闲时间段 - 时间填报功能
     * 前端接口: POST /schedule/time-report/availability
     */
    @PostMapping("/time-report/availability")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<ApiResponse<Void>> createUserAvailability(
            @RequestBody TimeSlotRequestDTO request,
            HttpServletRequest httpRequest) {
        try {
            // 从请求头中获取JWT token并解析用户ID
            String authorizationHeader = httpRequest.getHeader("Authorization");
            if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
                return ResponseEntity.ok(ApiResponse.error("未找到有效的认证token"));
            }

            String token = authorizationHeader.substring(7); // 移除"Bearer "前缀
            Integer userId;
            try {
                userId = jwtTokenUtil.getUserIdFromToken(token);
                if (userId == null) {
                    return ResponseEntity.ok(ApiResponse.error("无法从token中获取用户ID"));
                }
            } catch (Exception e) {
                return ResponseEntity.ok(ApiResponse.error("token解析失败: " + e.getMessage()));
            }

            // 转换DTO为实体对象
            List<UserAvailability> availabilityList = new ArrayList<>();
            for (TimeSlotRequestDTO.TimeSlotDTO timeSlot : request.getTimeSlots()) {
                UserAvailability availability = new UserAvailability();
                availability.setUserId(userId);
                availability.setDayOfWeek(timeSlot.getDayOfWeek());
                availability.setStartTime(LocalTime.parse(timeSlot.getStartTime()));
                availability.setEndTime(LocalTime.parse(timeSlot.getEndTime()));
                // 将isPreferred映射为isAvailable
                availability.setIsAvailable(timeSlot.getIsPreferred() != null ? timeSlot.getIsPreferred() : true);
                availability.setCreatedAt(java.time.LocalDateTime.now());
                availability.setUpdatedAt(java.time.LocalDateTime.now());

                availabilityList.add(availability);
            }

            // 更新用户周可用时间（智能比对更新模式）
            boolean success = userAvailabilityService.updateUserWeeklyAvailability(userId, availabilityList);

            if (success) {
                return ResponseEntity.ok(ApiResponse.success("用户空闲时间选择成功", null));
            } else {
                return ResponseEntity.ok(ApiResponse.error("用户空闲时间选择失败"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("用户空闲时间选择失败: " + e.getMessage()));
        }
    }
}